<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          总记录数: {{ total }}条
        </template>
        <template #right>
          <el-button size="mini" type="warning" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button size="mini" type="danger" @click="handleDownload">excel导出</el-button>
          <el-button size="mini" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table
          v-loading="loading"
          border
          stripe
          :data="list"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
        >
          <el-table-column type="index" :index="methodIndex" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img v-error="defaultImg" class="staff" :src="row.staffPhoto || defaultImg" alt="" @click="showCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatter" sortable="" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry | format('YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="联系方式" sortable="" />
          <!-- <el-table-column prop="enableState" label="账户状态" sortable="" /> -->
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button
                type="text"
                size="small"
                :disabled="row.mobile === '13800000002'"
                @click="$router.push('/employees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="clickShowRoleDialog(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delItem(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[10,20,30,40]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <add-employees :show-dialog.sync="showDialog" />
    <el-dialog style="text-align: center;" width="300px" title="二维码" :visible="showCodeDialog" :before-close="isShowCode">
      <canvas ref="myCanvas" />
    </el-dialog>
    <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { format } from '@/filters/index'
import employeesEnu from '@/api/constant/employees.js'
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import addEmployees from './components/add-employees'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role'
export default {
  name: 'Employees',
  components: {
    addEmployees,
    AssignRole
  },
  data() {
    return {
      page: 1,
      size: 10,
      list: [],
      total: 0,
      loading: false,
      showDialog: false,
      defaultImg: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1689344884,3991998886&fm=26&gp=0.jpg',
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    async getEmployee() {
      this.loading = true
      const { data: { total, rows }} = await reqGetEmployeeList(this.page, this.size)
      console.log(rows)
      // 将字符串转成数字类型
      this.list = rows.map(item => {
        item.formOfEmployment = +item.formOfEmployment
        return item
      })
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleSizeChange(newSize) {
      console.log(newSize)
      this.size = newSize
      this.getEmployee()
    },
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.page = newPage
      this.getEmployee()
    },
    methodIndex(index) {
      return index + 1 + (this.page - 1) * (this.size)
    },
    delItem(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { message } = await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success(message)
        this.getEmployee()
      }).catch(() => {
        this.$message.info('删除失败')
      })
    },
    formatter(row) {
      // console.log(row.formOfEmployment)
      // return row.formOfEmployment === 1 ? 'ok' : 'no'
      // 遍历数组 返回对应的value
      const res = employeesEnu.hireType.find(item => item.id === row.formOfEmployment)
      // console.log(res)
      return res ? res.value : '未知'
    },
    async handleDownload() {
      // 获取员工数据
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const transformRows = rows.map(item => {
        item.formOfEmployment = +item.formOfEmployment
        return item
      })
      // 导入表格
      import('@/vendor/Export2Excel').then(excel => {
        // const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const dataArr = this.formatJson(transformRows, headersRelations)
        console.log(excel)
        excel.export_json_to_excel({
          header: Object.keys(headersRelations),
          data: dataArr,
          filename: '哈哈哈',
          autoWidth: 'autoWidth',
          bookType: 'xlsx',
          multiHeader, // 复杂表头
          merges // 合并配置项
        })
      })
    },
    // 将表头数据和数据进行对应
    formatJson(rows, headersRelations) {
      // [
      //   [ 值1, 值2, 值3, ... ]
      // ]
      const resultsArr = rows.map(item => {
        const arr = []
        Object.keys(headersRelations).forEach(key => {
          const englishKey = headersRelations[key]
          // 做时格式的处理
          let value = item[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            // 导入时间格式化的方法
            value = value ? format(value) : '未填写'
          }
          if (englishKey === 'formOfEmployment') {
            const o = employeesEnu.hireType.find(obj => obj.id === value)
            value = o ? o.value : '未知'
          }
          arr.push(value)
        })
        return arr
      })
      return resultsArr
    },
    showCode(url) {
      if (!url) return
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    isShowCode() {
      this.showCodeDialog = false
    },
    clickShowRoleDialog(id) {
      this.userId = id
      this.showRoleDialog = true
    }
  }

}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
